<template>
  <div class="screenBox">
    <input type="file" id="imageInput" accept="image/*" @change="handleFile" />
    <canvas id="canvas" style="display: none"></canvas>
    <img id="croppedImage" alt="Cropped Image" />
  </div>
</template>

<script lang="ts" setup>
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";
import { onMounted } from "vue";
let cropper: any = null;
const handleCropper = (image: any) => {
  // 第一个参数必须是添加到dom中img标签
  cropper = new Cropper(image, {
    // viewMode: 1,
    // dragMode: "none",
    // initialAspectRatio: 1,
    // aspectRatio: 1, //裁剪比例
    // preview: ".before",
    // background: false,
    // autoCropArea: 0.6,
    // zoomOnWheel: false,
    aspectRatio: 16 / 9, // 设置裁剪比例
    viewMode: 1, // 限制裁剪区域的大小
    guides: false, // 不显示裁剪区域的虚线
    crop(event) {
      // 裁剪回调
      console.log(
        event.detail.x,
        event.detail.y,
        event.detail.width,
        event.detail.height
      );
      getCroppedCanvas();
    },
  });
};

const getCroppedCanvas = () => {
  const croppedCanvas = cropper.getCroppedCanvas({
    width: 300, // 设置裁剪后的图片宽度
    height: 300, // 设置裁剪后的图片高度
    minWidth: 100,
    minHeight: 100,
    maxWidth: 3000,
    maxHeight: 3000,
    fillColor: "transparent", // 背景颜色
    imageSmoothingEnabled: false,
    imageSmoothingQuality: "high",
  }); // 获取裁剪后的Canvas
  croppedCanvas.toBlob((blob: any) => {
    // 处理裁剪后的blob，例如上传到服务器或显示在页面上
    const url = URL.createObjectURL(blob);
    // 显示截取后的图片
    const resDom: any = document.getElementById("croppedImage");
    resDom.src = url;
  });
  // var dataUrl = croppedCanvas.toDataURL('image/jpeg', 0.9); // 0.9为图片质量
  // const resDom: any = document.getElementById("croppedImage");
  // resDom.src = dataUrl;
};

const handleFile = (event: any) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = function (e: any) {
      const img: any = new Image();
      document.body.appendChild(img);
      img.onload = function () {
        // const canvas: any = document.getElementById("canvas");
        // const ctx = canvas.getContext("2d");
        // // 设置canvas尺寸
        // canvas.width = 300; // 指定宽度
        // canvas.height = 200; // 指定高度
        // // 绘制图片到canvas
        // ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        // // 获取截取后的图片数据
        // const croppedDataUrl = canvas.toDataURL("image/png");
        // // 显示截取后的图片
        // const resDom: any = document.getElementById("croppedImage");
        // resDom.src = croppedDataUrl;
        handleCropper(img);
      };
      img.src = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};

onMounted(() => {});
</script>

<style scoped lang="scss">
.screenBox {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-content: center;
}
</style>
